/**
 * 2017年1月6日
 */
package algorithm.xml;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
 * @author Alex
 *
 */
class Node{
	public String name;
	public Attributes atts;
	public ArrayList<Node> chidren = new ArrayList<>(10);
	Node parent = null;
	public String toString(){
		return name+",children:"+this.chidren.size();
	}
}
class ParseEndObserve implements Observer{
	@Override
	public void update(Observable o, Object arg) {
		System.out.println("end");
	}
	
}

public class XMLParser {
	static class Handler extends DefaultHandler{
		Observable obs = new Observable();
		public static Node root = null;
		Node cur  = null;
		public void addObserver(Observer o){
			this.obs.addObserver(o);
		}
		public void endDocument() throws SAXException {
		}

		public void startDocument() throws SAXException {

			super.startDocument();
		}

		public void startElement(String uri, String localName, String qName, Attributes attributes)
				throws SAXException {
			switch(qName){
				
			case "root":
				root = new Node();
				root.name = qName;
				root.atts = attributes;
				cur = root;
				break;
			case "employee":
				Node n = new Node();
				n.name = qName;
				n.atts = attributes;
				cur.chidren.add(n);
				n.parent = cur;
				cur = n;
				break;
			case "name":
				Node n1 = new Node();
				n1.name = qName;
				cur.chidren.add(n1);
				break;
			case "sex":
				Node n2 = new Node();
				n2.name = qName;
				cur.chidren.add(n2);
				break;

			case "age":
				Node n3 = new Node();
				n3.name = qName;
				cur.chidren.add(n3);	
				break;
				
			}

		}
		public void endElement(String uri, String localName, String qName) throws SAXException {
			switch(qName){
			case "root":
//				obs
				obs.notifyObservers();
				break;
			case "employee":
				cur = cur.parent;
				break;
			case "name":		
				break;
			case "sex":		
				break;
			case "age":	
				break;
			
			}
		}
		
	}
	public static void main(String[] args) throws Exception {
		SAXParserFactory fac =SAXParserFactory.newInstance();
		SAXParser parser = fac.newSAXParser();
		Handler h = new Handler();
		h.addObserver((Observable o, Object arg)->{System.out.println(o);});
		parser.parse(XMLParser.class.getResourceAsStream("test.xml"), h);
		Node root = h.root;
		traverseRoot(root);
	}
	public static void traverseRoot(Node n){
		if(n!=null){
			System.out.println(n.name);
		}else{
			return ;
		}
		if(n.chidren!=null){
			for(Node c:n.chidren){
				traverseRoot(c);
			}
			
		}
		
		
	}
	
	

}
